/**
 * 
 */
package demo.timer;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.lang3.time.DurationFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author roger.xu
 * 
 */
public class DemoUpdater {
    private static final Log _log = LogFactory.getLog(DemoUpdater.class.getSimpleName());

    private static final String NAME = DemoUpdater.class.getSimpleName();

    private static final Timer timer = new Timer(NAME);

    private static final TimerTask task = new TimerTask() {
        @Override
        public void run() {
            _log.info("Updating data...");

        }
    };

    /**
     * Start updater and execute task once per day.
     */
    public static void start() {
        final long period = DateUtils.MILLIS_PER_DAY;
        start(period);
    }

    /**
     * Start updater with specified period.
     * 
     * @param period
     *            Amount of time between executions.
     */
    public static void start(long period) {
        _log.info("start " + NAME);

        final Calendar tomorrow = Calendar.getInstance();
        // tomorrow.set(Calendar.HOUR, 0);
        // tomorrow.set(Calendar.MINUTE, 0);
        // tomorrow.set(Calendar.SECOND, 0);
        _log.debug("when: " + tomorrow.getTime().toString());
        _log.debug("period: " + DurationFormatUtils.formatDurationWords(period, true, true));

        timer.scheduleAtFixedRate(task, tomorrow.getTime(), period);
    }

    /**
     * End updater.
     */
    public static void end() {
        _log.info("end " + NAME);
        timer.cancel();
    }

}
